<script setup lang="ts">
import Pagination from "@/components/pagination/index.vue";
import { Search } from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import { fetchPostGoods, fetchPutGoods } from '@/api/goods'
import { filterDate } from '@/utils/format'
import type { FormInstance, FormRules } from "element-plus";
import { fetchGoodsApplyList } from '@/api/goods/apply'
import { usePublicStoreHook } from "@/store/modules/public";
import InfoDialog from './infoDialog.vue'
import { fetchGoodsRecordList } from '@/api/goods/record'


let showInfoDialog = ref(false); // 是否展示物资信息编辑框
let goodsFormDialog = ref(false);
// 表单数据
let tableData = reactive([])
// 实际传递的条件
const listQuery = reactive({
  currentPage: 1,
  name: undefined, // 名称
  type: undefined, // 类型
  status: 1, // 审批状态
  pageSize: 10,
  form: undefined, // 活动形式
})
// 显示在界面上的查询条件
const showQuery = reactive({
  currentPage: 1,
  name: undefined, // 名称
  type: undefined, // 类型
  form: undefined, // 活动形式
  status: 1, // 审批状态
})
const total = ref<number>(0)// 列表总数
// 查询
const handleSearch = () => {
  getPageList()
}
const tableLoading = ref(false)
// 获取列表
const getPageList = async () => {
  tableLoading.value = true
  listQuery.name = showQuery.name
  listQuery.status = showQuery.status
  listQuery.type = showQuery.type
  const res = await fetchGoodsApplyList(listQuery)
  const { currentPage, data } = res.data
  listQuery.currentPage = showQuery.currentPage = currentPage
  total.value = res.data.total
  tableData = data
  tableLoading.value = false
}
onMounted(() => {
  getPageList()
})
/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
  // 重置验证规则
  if (!formEl) return;
  showInfoDialog.value = false
  ruleForm = {
    id: 0,
    type: 0,
    name: '', // 名称
    price: "", // 单价
    inputNum: "", // 数量
    unit: "", // 单位
    goodsInfo: "", // 备注
    category: 0,
  }
  formEl.resetFields();
};
let ruleForm = reactive({
  id: 0,
  type: 0,
  name: '', // 名称
  price: "", // 单价
  inputNum: "", // 数量
  unit: "", // 单位
  goodsInfo: "", // 备注
  category: 0,
});
const typeOptions = [
  {
    value: 0,
    label: '领用申请'
  },
  {
    value: 1,
    label: '借用申请'
  }
]
const ruleFormRef = ref<FormInstance>();
const title = ref('')
const rules = reactive<FormRules>({
  type: [{ required: true, message: "请选择物资类型", trigger: "change" }],
  name: [{ required: true, message: "请输入物资名称", trigger: "change" }],
  price: [{ required: true, message: "请输入物资单价", trigger: "change" }],
  inputNum: [{ required: true, message: "请输入入库数量", trigger: "change" }],
  unit: [{ required: true, message: "请输入入库单位", trigger: "change" }],
  goodsInfo: [{ required: true, message: "请输入物资信息", trigger: "change" }],
});

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (title.value === '新增物资') {
        fetchPostGoods(ruleForm).then((res: { code: number; }) => {
          if (res.code == 200) {
            ElMessage({
              message: '操作成功',
              type: 'success'
            })
          }
          showInfoDialog.value = false
          getPageList()
        })
      } else {
        fetchPutGoods(ruleForm).then((res: { code: number; }) => {
          if (res.code == 200) {
            ElMessage({
              message: '操作成功',
              type: 'success'
            })
          }
          showInfoDialog.value = false
          getPageList()
        })
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
let dialogData = ref({}) // 弹框数据
let recordData = ref({}) // 审批记录数据
/**
 * 查看
 */
const checkForm = (value: boolean, row?: object) => {
  // TODO 弹出查看表单
  goodsFormDialog.value = value;
  if (row) {
    const list = usePublicStoreHook().societyTypeList
    list.forEach(item => {
      if (item.id == row.type) {
        row.type = item.name
      }
    })
    dialogData.value = row
    // 获取物资审批记录
    fetchGoodsRecordList(dialogData.value.id).then(res => {
      recordData.value = res.data
    })
  } else {
    getPageList()
  }
};
</script>

<template>
  <div class="goods-form-container">
    <div class="header flex justify-between items-center">
      <div class="flex items-center justify-between">
        <el-select v-model="showQuery.type" class="m-2" placeholder="根据申请类型查询" clearable>
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input v-model="showQuery.name" placeholder="根据物资名称查询" clearable />
        <el-button type="primary" :icon="Search" class="btn-green" @click="handleSearch()">查询</el-button>
      </div>
    </div>
    <el-table :data="tableData" stripe style="min-height: 40rem">
      <el-table-column type="index" label="序号" width="100" />
      <el-table-column prop="type" label="申请类型" show-overflow-tooltip>
        <template #default="scope">
          <div class="theme-blue">{{ scope.row.applyType == 0 ? '领用申请' : '借用申请' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="申请人" show-overflow-tooltip>
        <template #default="scope">
          <div>{{ scope.row.User.name }}</div>
        </template>
      </el-table-column>
      <el-table-column label="申请物资" show-overflow-tooltip>
        <template #default="scope">
          <div>{{ scope.row.Good.name }}</div>
        </template>
      </el-table-column>
      <el-table-column label="申请数量">
        <template #default="scope">
          <div>{{ scope.row.applyNumber }}</div>
        </template>
      </el-table-column>
      <el-table-column label="物资单价(元)">
        <template #default="scope">
          <div>{{ scope.row.Good.price }}</div>
        </template>
      </el-table-column>
      <el-table-column label="物资信息" show-overflow-tooltip>
        <template #default="scope">
          <div>{{ scope.row.Good.goodsInfo }}</div>
        </template>
      </el-table-column>
      <el-table-column label="申请时间">
        <template #default="scope">
          <div>{{ filterDate(scope.row.createdAt) }}</div>
        </template>
      </el-table-column>

      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <div class="theme-blue" v-if="scope.row.status == 0">待审批</div>
          <div class="theme-success" v-if="scope.row.status == 1">已同意-待领取</div>
          <div class="theme-error" v-if="scope.row.status == 2">已驳回</div>
          <div class="theme-warn" v-if="scope.row.status == 3">已领取-待归还</div>
          <div class="theme-blue" v-if="scope.row.status == 4">归还-待审批</div>
          <div class="theme-success" v-if="scope.row.status == 5">已归还</div>
          <div class="theme-error" v-if="scope.row.status == 6">拒绝归还</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <div class="theme-success">
            <el-button type="primary" class="btn-white" @click="checkForm(true, scope.row)">查看</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination :total="total" v-model:page="listQuery.currentPage" v-model:limit="listQuery.pageSize" hide-on-single-page
      @pagination="getPageList" />
    <!-- 查看弹框 -->
    <InfoDialog ref="infoDialog" :goodsFormDialog="goodsFormDialog" @closeDialog="checkForm(false)"
      :dialogData="dialogData" :recordData="recordData" />
  </div>
</template>

<style lang="scss">
.goods-form-container {
  .header {
    height: 70px;

    .el-input {
      margin-right: 20px;
    }

    .el-input,
    .el-select {
      margin-right: 20px;
      width: 20rem;
    }
  }
}
</style>
